<?php 
class Flashgallery extends CI_Model {
	public function getImages() {
		$allImages = array();
		
		$xdoc = new DOMDocument();
		$xdoc->load(FCPATH.'/images.xml', LIBXML_NOCDATA);
		$images = $xdoc->getElementsByTagName('images')->item(0);
		$photos = $images->getElementsByTagName('photo');
		foreach ($photos as $photo) {
			$imageText = str_replace(array('<head>', '</head>'), '', $photo->nodeValue);
			$imageInfo = array('image' => $photo->getAttribute('image'), 'text' => $imageText);
			
			$allImages[] = $imageInfo;
		}
		
		return $allImages;
	}
	
	public function addImage($name, $text) {
		$xdoc = new DOMDocument();
		$xdoc->load(FCPATH.'images.xml');
		$images = $xdoc->getElementsByTagName('images')->item(0);
		$newImage = $xdoc->createElement("photo");
		$cdata = $xdoc->createCDATASection("<head>".nl2br($text)."</head>");
		$newImage->appendChild($cdata);
		$newImage->setAttribute('image', 'uploads/gallery/images/'.$name);
		$newImage->setAttribute('target', '_blank');
		$images->appendChild($newImage);
		$xdoc->save(FCPATH.'images.xml');
	}
	
	public function deleteImage($hash) {
		// Delete from XML
		$xdoc = new DOMDocument();
		$xdoc->load(FCPATH.'images.xml');
		$images = $xdoc->getElementsByTagName('images')->item(0);
		$photos = $images->getElementsByTagName('photo');
		
		foreach ($photos as $photo) {
			if (md5($photo->getAttribute('image')) == $hash) {
				$delImage = $photo->getAttribute('image');
				$xdoc->documentElement->removeChild($photo);
				
			}
		}
		$xdoc->save(FCPATH.'images.xml');
		// Delete from filesystem
		unlink(FCPATH.$delImage);
	}
}
?>